var page = require('webpage').create();
var fs = require('fs');
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36';
page.viewportSize = {
  width: 1280,
  height: 800
};
page.open('http://edit.newrank.cn', function(status) {
	if(status == "success") {
		console.log("open success");
		if(page.injectJs('../baidu/clickFunction.js')) {
			console.log("include js success");
			page.evaluate(function() {
				ele_click(document.getElementsByClassName('left-menu-item-pics')[0]);
			})
			
		}
		
		function getInfo() {
			var readyState = page.evaluate(function () {
				return document.readyState;
			});
			console.log("ready status "+readyState);
			var timer = setInterval(function() {
				var allLength = page.evaluate(function() {
					var liLength = document.getElementsByClassName('article-right-li').length;
					console.log("inner length : " + liLength);
					return liLength;
				})
				if(allLength > 0) {
					clearInterval(timer);
					var data = {};
					var myData = page.evaluate(function(length, Data) {
						for(var i = 0; i < length; i++) {
							var dataJson = {}, linkWrap = document.getElementsByClassName('article-right-li')[i];
							
							dataJson["titleUrl"] = linkWrap.getAttribute('data-url');
							
							var title = linkWrap.getElementsByClassName('article-title-val')[0].getAttribute('title');
							dataJson['title'] = title;
							
							var countRead = linkWrap.getElementsByClassName('article-type-span-yuedu')[0].innerText;
							dataJson['read'] = countRead;
							
							var countZan = linkWrap.getElementsByClassName('article-zan-shu')[0].innerText;
							dataJson['zan'] = countZan;
							
							var assortment = linkWrap.getElementsByClassName('article-type-span')[1].getAttribute('title');
							dataJson['assortment'] = assortment;
							
							var editor = linkWrap.getElementsByClassName('article-right-btn')[0];
							console.log(editor);
							if(editor == undefined) {
								dataJson['flagOriginal'] = false;
							}else {
								dataJson['flagOriginal'] = true;
							}
							Data[i] = dataJson;
						}
						return Data;
					}, allLength, data)
					
					var last = JSON.stringify(myData);
					fs.write('xinbang.txt', last, 'a');
				}
			}, 200)
			
			
		}
		setTimeout(function() {
			getInfo();
		}, 200) 
	}else {
		console.log("fail open");
	}
})

page.onConsoleMessage = function(msg) {
    console.log('console: ' + msg);
};